/**
 * 
 */
package domain;

import java.util.*;

/**
 * @author it-equipment-selection team
 *
 */
public class ContractTableQuery implements IQuery {

	/* (non-Javadoc)
	 * @see domain.IQuery#productQuery(java.util.Collection)
	 * @returns most voted products Collection
	 */
	/*public Collection productQuery(Collection products, Collection articles) {
		Collection aux = new ArrayList();
		Iterator ita = articles.iterator();
		while (ita.hasNext()){
			Article a = (Article) ita.next();
			Iterator itp = products.iterator();
			int votos = -1;
			Product paux = null;
			while (itp.hasNext()){
				Product p = (Product) itp.next();
				if (p.getArticle().equals(a) && p.getNumVotes() > votos){
					votos = p.getNumVotes();
					paux = p;
				}
			}
			if (aux!=null)
				aux.add(paux);
		}
		return aux;
	}*/
	/* (non-Javadoc)
	 * @see domain.IQuery#productQuery(java.util.Collection)
	 * @returns most voted products Collection
	 */
	/*public Collection productQuery(Collection products, Collection articles) {
		Collection aux = new ArrayList();
		Collection<Article> ar=articles;
		Collection<Product> pr=products;
		for(Article a:ar){
			Product paux = (Product)maxVotes(pr,a);
			aux.add(paux);
			for(Product p:pr){
				if(p.getArticle().equals(paux.getArticle())&& !p.equals(paux)&& p.getNumVotes()==paux.getNumVotes())
					//if (p.isValid()) //prueba
						aux.add(p);
			}
		}
	
		return aux;
	}
	
	private Product maxVotes (Collection products, Article a){
		Product paux = null;
	    Iterator it = products.iterator();
			int votos = -1;
			while (it.hasNext()){
				Product p = (Product) it.next();
				if (p.getArticle().equals(a) && p.getNumVotes() > votos){
					votos = p.getNumVotes();
					paux = p;

				}
			}
			return paux;
	}*/
	public Collection productQuery(Collection products, Collection articles) {
		Collection aux = new ArrayList();
		Collection aux2 = new ArrayList();
		Iterator ita = articles.iterator();
		while (ita.hasNext()){
			Article a = (Article) ita.next();
			Iterator itp = products.iterator();
			int votos = -1;
			Product paux = null;
			while (itp.hasNext()){
				Product p = (Product) itp.next();
				if (p.getArticle().equals(a) && p.getNumVotes() > votos){
					votos = p.getNumVotes();
					paux = p;
				}
			}
			if (aux!=null)
				aux.add(paux);
			
			aux2 = empate(products, a, votos, aux);
			aux.addAll(aux2);
			
		}
		return aux;
	}
	
	public Collection empate(Collection products, Article a, int maxVoto, Collection aux){
		Collection aux2 = new ArrayList();
		Iterator itp = products.iterator();
		while (itp.hasNext()){
			Product p = (Product) itp.next();
			if (p.getArticle().equals(a) && p.getNumVotes() == maxVoto && !aux.contains(p)){
					aux2.add(p);
			}
		}
		return aux2;
	}

}
